package com.gzhu.knowledgeAdmin.service.impl;

import com.gzhu.knowledgeAdmin.common.exception.BusinessException;
import com.gzhu.knowledgeAdmin.common.result.ErrorCode;
import com.gzhu.knowledgeAdmin.repository.VariableTypeRepository;
import com.gzhu.knowledgeAdmin.entity.VariableType;
import com.gzhu.knowledgeAdmin.service.VariableTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class VariableTypeServiceImpl implements VariableTypeService {

    @Autowired
    private VariableTypeRepository variableTypeRepository;

    @Override
    public List<String> getVariables() {
        List<VariableType> variableTypeList = variableTypeRepository.findAll();

        return variableTypeList.stream().map(VariableType::getName).collect(Collectors.toList());
    }

    @Override
    public List<VariableType> getVariablesList() {
        return variableTypeRepository.findAll();
    }

    @Override
    public boolean addVariable(String name) {
        VariableType variableTypeByName = variableTypeRepository.getVariableTypeByName(name);

        if (variableTypeByName != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数已经存在!");
        }

        VariableType variableType = new VariableType();
        variableType.setName(name);
        variableTypeRepository.save(variableType);
        return true;
    }

    @Override
    public void deleteVariable(Integer id) {

        try {
            variableTypeRepository.deleteById(id);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"id不存在!");
        }

    }
}
